/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.persistence.util;

import org.apache.commons.lang.StringUtils;

/**
 * Utilities to deal with queries.
 * 
 * @since 1.0
 */
public abstract class QueryUtils {

	public static final String LIKE_ANY_TOKEN = "%";
	public static final String ESCAPED_LIKE_ANY_TOKEN = "\\%";
	public static final String LIKE_SINGLE_TOKEN = "_";
	public static final String ESCAPED_LIKE_SINGLE_TOKEN = "\\_";

	public static String forLike(String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		}
		
		StringBuilder sb = new StringBuilder();
		sb.append(LIKE_ANY_TOKEN);
		sb.append(escape(value));
		sb.append(LIKE_ANY_TOKEN);
		
		return sb.toString();
	}
	
	public static String forStartsWith(String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		}
		
		StringBuilder sb = new StringBuilder();
		sb.append(LIKE_ANY_TOKEN);
		sb.append(escape(value));
		
		return sb.toString();
	}

	public static String escape(String valueToEscape) {
		String escapedValue = StringUtils.replaceChars(valueToEscape, LIKE_ANY_TOKEN, ESCAPED_LIKE_ANY_TOKEN);
		return StringUtils.replaceChars(escapedValue, LIKE_SINGLE_TOKEN, ESCAPED_LIKE_SINGLE_TOKEN);
	}

}
